package com.atguigu.srb.core.schedule;

import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.core.pojo.entity.LendReturn;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.LendReturnService;
import com.atguigu.srb.core.service.UserInfoService;
import com.atguigu.srb.mq.consts.MqConsts;
import com.atguigu.srb.mq.service.MqService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.joda.time.DateTime;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class SrbTask {
    @Resource
    UserInfoService userInfoService;
    @Resource
    LendReturnService lendReturnService;
    @Resource
    MqService mqService;
    //每过5秒钟执行一次
    @Scheduled(cron = "0/20 * * * * ? ") //cron: Scheduled支持6位的表达式
    public void sendLendReturnMsg(){
        //System.out.println(new Date());
        //提醒的还款时间区间：[ 6-23 6-22 6-21 6-20 ]
        //查询还款计划表，如果有临近还款的记录 给用户发送短信通知准备还款
        List<LendReturn> lendReturns = lendReturnService.list(Wrappers.lambdaQuery(LendReturn.class)
                .eq(LendReturn::getStatus, 0)
                .le(LendReturn::getReturnDate,
                        new DateTime().plusDays(3).toString("yyyy-MM-dd")));
        if(CollectionUtils.isEmpty(lendReturns)){
            return;
        }
        lendReturns.forEach(lendReturn -> {
            Long userId = lendReturn.getUserId();
            UserInfo userInfo = userInfoService.getById(userId);
            mqService.sendMsg(MqConsts.EXCHANGE_TOPIC_SMS,MqConsts.ROUTING_SMS_ITEM,
                    new SmsDTO(userInfo.getMobile(),6, Arrays.asList("xxxx")));
        } );
    }

}
